<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Request;


class Login extends Controller
{
    public function index()
    {
        //加载模板
        return view('login/login', [
            'title' => '登录页面'

        ]);
    }

   public function login()
    {
        $username = $_POST['username'];
        $pass = md5($_POST['password']);
        //dump($username);
        //dump($pass);die;
        //判断用户是否存在
        $data = Db::name('user')
            ->where('username', $username)->where('pass', $pass)
            ->where('status', 1)
            ->field('pass',true)->find();//禁用用户不允许登录
        //dump($result);
        if(!empty($data)){
            //把用户信息添加到session
            session('admin_user',$data);
            $uid = session('admin_user')['id'];
            //更改登录状态信息
            $data['logintime'] = time();
            $data['loginip'] = $_SERVER['REMOTE_ADDR'];
            Db::name('user')->where('id',$uid)->update($data);


            //根据用户id获取对应的角色id
            $role_id = Db::name('user_role')->where('user_id',$uid)->field('role_id')->select();
            //dump($role_id);die;
            foreach($role_id as $val){
                //根据角色id获取对应的节点id
                $node_id[] = Db::name('role_node')->where('role_id',$val['role_id'])->select();
            }
            //dump($node_id);die;
            $list = array();
            //第三条 根据节点id 查到节点
            foreach($node_id[0] as $val){
                $list[] = Db::name('node')->where('id',$val['node_id'])->find();
            }
            //dump($list);die;
            //session('nodelist',$list);
            //dump(session('nodelist'));die;

            //控制器名转换为大写
            foreach ($list as $key => $val) {
                $list[$key]['controller'] = ucfirst($val['controller']);
            }
            $nodelist = array();
            $nodelist['Index'] = array('index');
            //dump($list);die;
            //遍历重新拼装
            foreach($list as $val){
                //dump($val['action']);die;
                $nodelist[$val['controller']][] = @$val['action'];
                //把修改和执行修改 添加和执行添加 拼装到一起
                if(@$val['action']=="edit"){
                    $nodelist[$val['controller']][]="update";
                }
                if(@$val['action']=="create"){
                    $nodelist[$val['controller']][]="save";
                }
            }
            //转存session
            session('nodelist',$nodelist);
            //dump(session('nodelist'));die;

            //跳转到首页
            $this->success('登录成功！',url('admin/user/index'));
        } else {
            $this->error('您的用户名或密码输入有误，请重新输入！',url('admin/login/index'));
        }
    }
    //退出登陆
    public function logout()
    {
        //清空session
        unset($_SESSION['admin_user']);
        //跳转
        $this->redirect('index/index');
    }

}